package com.atguigu.gmall.index.config;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.index.feign.GmallPmsClient;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Configuration
public class BloomFilterConfig {
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    GmallPmsClient gmallPmsClient;
    private static final String KEY_PREFIX="index:cates:[";
    
    @Bean
    public RBloomFilter bloomFilter(){
        //把所有的分类id都查出来，加入到布隆过滤器中
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter("index:bloom");
        bloomFilter.tryInit(10000,0.03);
        ResponseVo<List<CategoryEntity>> catesResponseVo = gmallPmsClient.queryCategoriesByPid(0L);
        List<CategoryEntity> categoryEntities = catesResponseVo.getData();
        if(!CollectionUtils.isEmpty(categoryEntities)){
            categoryEntities.forEach(categoryEntity -> {
                bloomFilter.add(KEY_PREFIX+categoryEntity.getId()+"]");
            });
        }
        return bloomFilter;
    }

}
